package com.sinosoft.system.primary.realm;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.sinosoft.system.primary.dao.imp.SysButtonRelDaoJdbc;
import com.sinosoft.system.primary.dao.imp.SysMenuDaoJdbc;
import com.sinosoft.system.primary.dao.imp.SysRoleDaoJdbc;
import com.sinosoft.system.primary.entity.SysButtonRel;
import com.sinosoft.system.primary.entity.SysRole;
import com.sinosoft.system.primary.dao.imp.SysUserDaoJdbc;
import com.sinosoft.system.primary.entity.SysUser;


public class MyRealm extends AuthorizingRealm{
	
	private static final Logger log = Logger.getLogger(MyRealm.class);
	
	@Autowired
	private SysUserDaoJdbc sysUserDao;
	
	@Autowired
	private SysRoleDaoJdbc sysRoleDao;
	
	@Autowired
	private SysMenuDaoJdbc sysMenuDao;
	
	@Autowired
	private SysButtonRelDaoJdbc sysButtonRelDao;
	/** 
     * 为当前登录的Subject授予角色和权限 
     * @see 经测试:本例中该方法的调用时机为需授权资源被访问时 
     * @see 经测试:并且每次访问需授权资源时都会执行该方法中的逻辑,这表明本例中默认并未启用AuthorizationCache 
     * @see 个人感觉若使用了Spring3.1开始提供的ConcurrentMapCache支持,则可灵活决定是否启用AuthorizationCache 
     * @see 比如说这里从数据库获取权限信息时,先去访问Spring3.1提供的缓存,而不使用Shior提供的AuthorizationCache 
     */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		log.info("start AuthorizationInfo");
		System.out.println("开始授权-----------------"); 
		principals= SecurityUtils.getSubject().getPrincipals();
		String currentUsername = (String)super.getAvailablePrincipal(principals); 
		SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
		List<SysRole> sysRoles = sysRoleDao.selectByUserId(0);
		if(sysRoles!=null && !sysRoles.isEmpty()){
			for (SysRole sysRole : sysRoles) {  
				simpleAuthorInfo.addRole(sysRole.getRoleCode());
            }
			//添加权限  
			List<SysButtonRel> sysButtonRels = sysButtonRelDao.selectRoleSysButtonRels(sysRoles);
			if(sysButtonRels!=null && !sysButtonRels.isEmpty()){
				for (SysButtonRel sysButtonRel : sysButtonRels) {  
					simpleAuthorInfo.addStringPermission(sysButtonRel.getMenuCode()+":"+sysButtonRel.getButtonCode());
	            }
			}
            return simpleAuthorInfo;
		}else {  
            System.out.println("当前用户无授权");  
            return simpleAuthorInfo;  
        }
	}

	/** 
     * 验证当前登录的Subject 
     * @see 经测试:本例中该方法的调用时机为LoginController.login()方法中执行Subject.login()时 
     */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken)authcToken;  
        System.out.println("验证当前Subject时获取到token为" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));
      //此处无需比对,比对的逻辑Shiro会做,我们只需返回一个和令牌相关的正确的验证信息  
        //说白了就是第一个参数填登录用户名,第二个参数填合法的登录密码(可以是从数据库中取到的,本例中为了演示就硬编码了)  
        //这样一来,在随后的登录页面上就只有这里指定的用户和密码才能通过验证  
        String username = token.getUsername();
        String password = String.valueOf(token.getPassword());
        List<String> queryKeys = new ArrayList<String>();
        queryKeys.add("username");
        queryKeys.add("password");

        List<Object> queryValues = new ArrayList<Object>(); 
        queryValues.add(username);
        queryValues.add(password);
        SysUser sysUser = sysUserDao.selectSysUser(queryKeys, queryValues);
        if(sysUser!=null){ 
        	//String credential = UUIDGenerator.getUUID();
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(username, password, username);  
            this.setSession("currentUser", username); 
            this.doGetAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());//调用授权
            return authcInfo;  
        }
        return null;
	}
	/** 
     * 将一些数据放到ShiroSession中,以便于其它地方使用 
     * @see 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到 
     */  
    private void setSession(Object key, Object value){  
        Subject currentUser = SecurityUtils.getSubject();  
        if(null != currentUser){  
            Session session = currentUser.getSession();  
            System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");  
            if(null != session){  
                session.setAttribute(key, value);  
            }  
        }  
    }

	public SysUserDaoJdbc getSysUserDao() {
		return sysUserDao;
	}

	public void setSysUserDao(SysUserDaoJdbc sysUserDao) {
		this.sysUserDao = sysUserDao;
	}
	public SysRoleDaoJdbc getSysRoleDao() {
		return sysRoleDao;
	}
	public void setSysRoleDao(SysRoleDaoJdbc sysRoleDao) {
		this.sysRoleDao = sysRoleDao;
	}

}
